package com.ruoyi.equipment.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.dadiyang.equator.Equator;
import com.github.dadiyang.equator.FieldInfo;
import com.github.dadiyang.equator.GetterBaseEquator;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.equipment.domain.*;
import com.ruoyi.equipment.enums.QosEnum;
import com.ruoyi.equipment.mapper.TDrawerMapper;
import com.ruoyi.equipment.mapper.TEquipmentMapper;
import com.ruoyi.equipment.mapper.TUserLogMapper;
import com.ruoyi.equipment.service.MqttRuleService;
import com.ruoyi.equipment.util.EmqxUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

@Service
public class MqttRuleServiceImpl implements MqttRuleService {

    @Autowired
    private TDrawerMapper tDrawerMapper;

    @Autowired
    private TEquipmentMapper tEquipmentMapper;

    @Autowired
    private TUserLogMapper tUserLogMapper;


//    @Override
//    public Integer returnDrawer(String userLogId, String drawerId, String equipmentId, String drawerNo,String userId) {
//        //检查设备是否在线
//        try {
//            TEquipment tEquipment = tEquipmentMapper.selectTEquipmentByEquipmentId(equipmentId);
//            if (tEquipment.getStatus() == 1) {
//                throw new RuntimeException("设备不在线");
//            }
//            //检查仓匣是否存在于仓匣数据库中   修改
//            TDrawer drawer = tDrawerMapper.getDrawerByDrawerId(drawerId);
//            if (drawer.getDrawerStu() != 1) {
//                throw new RuntimeException("仓匣id错误,请联系管理人员");
//            }
//            //检查设备 仓匣号 是否在线 是否放有其他仓匣id
//            TDrawer tDrawer = tDrawerMapper.getDrawerByEquipmentIdAndDrawerNo(equipmentId, drawerNo);
//
//            if (tDrawer.getDrawerStatus() == 1 || tDrawer.getDrawerStu() == 0) {
//                throw new RuntimeException("设备仓匣号不在线,或者是仓匣id错误");
//            }
//            //修改用户记录里的仓匣归还状态
//            if (!StringUtils.isEmpty(userLogId)) {
//                TUserLog tUserLog = tUserLogMapper.selectTUserLogByUserId(Integer.parseInt(userLogId));
//                if (tUserLog != null) {
//                    if (tUserLog.getDrawerStu() == 0) {
//                        throw new RuntimeException("用户记录出现错误");
//                    }
//                }
//                tUserLog.setDrawerStu(0);
//                tUserLog.setRemark("仓匣已归还到设备上,请及时补充消息");
//                tUserLogMapper.updateTUserLog(tUserLog);
//            }
//            //修改之前drawerId 的状态
//            tDrawerMapper.updateTDrawerDrawerId(drawerId);
//
//            tDrawer.setDrawerStu(0);
//            tDrawer.setDrawerId(drawerId);
//            tDrawer.setDrawerRemark(drawer.getDrawerRemark());
//            tDrawer.setToolId(drawer.getToolId());
//            tDrawerMapper.updateTDrawer(tDrawer);
//        } catch (RuntimeException e) {
//            //上述步骤有错误
//            //归还失败 数据回滚
//            MqttVo mqttVo = new MqttVo();
//            mqttVo.setCode(3);
//            mqttVo.setUserLogId(userLogId);
//            mqttVo.setDrawerId(drawerId);
//            mqttVo.setEquipmentId(equipmentId);
//            mqttVo.setDrawerNo(drawerNo);
//            String payload = JSONObject.toJSONString(mqttVo);
//            String json = EmqxUtils.publish(equipmentId + "/code", equipmentId, payload, QosEnum.QoS2, false, EmqxUtils.getUrl() + "/api/v4/mqtt/publish");
//            //归还失败 修改备注
//            TUserLog tUserLog = new TUserLog();
//            tUserLog.setUserLogId(Integer.parseInt(userLogId));
//            tUserLog.setDrawerStu(2);
//            tUserLogMapper.updateTUserLog(tUserLog);
//            e.printStackTrace();
//        }
//        return 0;
//    }

    //弹出失败 设备告诉服务器 让服务器 修改日志 修改仓匣状态
    @Override
    public Integer popupError(String userLogId, String drawerId, String equipmentId, String drawerNo) {

        TUserLog tUserLog = new TUserLog();
        tUserLog.setUserLogId(Integer.parseInt(userLogId));
        tUserLog.setRemark("机柜id:" + equipmentId + "仓匣号:" + drawerNo + "借出失败");
        tUserLog.setDrawerStu(0);
        tUserLog.setReturnStu(0);
        //修改日志的状态
        tUserLogMapper.updateTUserLog(tUserLog);
        //根据仓匣id 仓匣号 修改状态
        TDrawer drawer = tDrawerMapper.getDrawerByDrawerId(drawerId);
        //修改仓匣的状态 为已经在仓匣里
        drawer.setDrawerStu(0);
        tDrawerMapper.updateTDrawer(drawer);
        return 0;
    }

    //设备第一次连接的问题
    @Override
    public Integer newConnectSet(ArrayList<MqttVo> mqttVoList) {
        for (MqttVo mqttVo : mqttVoList) {
            TDrawer tDrawer = new TDrawer();
            tDrawer.setEquipmentId(mqttVo.getEquipmentId());
            tDrawer.setDrawerNo(Integer.parseInt(mqttVo.getDrawerNo()));
            tDrawer.setDrawerStatus(0);
            tDrawer.setDrawerStu(0);
            tDrawer.setDrawerId(mqttVo.getDrawerId());
            tDrawerMapper.updateTDrawer(tDrawer);
        }

        return 0;
    }


    //检查仓匣的状态和数据库是否一致
    @Override
    public Integer checkedDrawer(ArrayList<DrawerVo> drawerVoList) {
        ArrayList<DrawerVo> drawerVoListDB = tDrawerMapper.selectDrawerVo(drawerVoList.get(0).getEquipmentId());
        //
        drawerVoListDB.sort(Comparator.comparing(DrawerVo::getDrawerId));
        drawerVoList.sort(Comparator.comparing(DrawerVo::getDrawerId));
        //存在不相等的数据了 开始更新数据库
        if (!drawerVoList.toString().equals(drawerVoListDB.toString())) {

            for (int i = 0; i < drawerVoList.size(); i++) {
                DrawerVo drawerVoDb = drawerVoListDB.get(i);
                DrawerVo drawerVo = drawerVoList.get(i);
                if (drawerVoDb.getDrawerId().equals(drawerVo.getDrawerId())
                        && drawerVo.getEquipmentId().equals(drawerVoDb.getEquipmentId())) {
                    if (!(drawerVoDb.getDrawerStu().equals(drawerVo.getDrawerStu()))) {
                        drawerVoDb.setDrawerStu(drawerVo.getDrawerStu());
                        //修改数据库数据 仓匣数据
                        TDrawer tDrawer = new TDrawer();
                        tDrawer.setDrawerStu(drawerVo.getDrawerStu());
                        tDrawer.setEquipmentId(drawerVo.getEquipmentId());
                        tDrawer.setDrawerNo(Integer.parseInt(drawerVo.getDrawerNo()));
                        tDrawerMapper.updateTDrawer(tDrawer);
                        //修改日志 内容
                        List<Integer> userLogId = tUserLogMapper.getUserLog(drawerVo.getDrawerId());
                        //将这些里面的内容 修改下
                        TUserLog tUserLog = new TUserLog();
                        tUserLog.setDrawerStu(0);
                        tUserLogMapper.updateTUserLog(tUserLog);
                        if (drawerVoList.toString().equals(drawerVoListDB.toString())) {
                            break;
                        }
                    }
                } else {
                    continue;
                }
            }

        }

        return 0;
    }



    @Override
    public Integer returnDrawer(String drawerId, String equipmentId, String drawerNo) {
        //取出最近的
        //检查设备是否在线
        String userLogId = tUserLogMapper.getUserLogId(drawerId);
        try {
            TEquipment tEquipment = tEquipmentMapper.selectTEquipmentByEquipmentId(equipmentId);
            if (tEquipment.getStatus() == 1) {
                throw new RuntimeException("设备不在线");
            }
            //检查仓匣是否存在于仓匣数据库中   修改
            TDrawer drawer = tDrawerMapper.getDrawerByDrawerId(drawerId);
            if (drawer.getDrawerStu() != 1) {
                throw new RuntimeException("仓匣id错误,请联系管理人员");
            }
            //检查设备 仓匣号 是否在线 是否放有其他仓匣id
            TDrawer tDrawer = tDrawerMapper.getDrawerByEquipmentIdAndDrawerNo(equipmentId, drawerNo);

            if (tDrawer.getDrawerStatus() == 1 || tDrawer.getDrawerStu() == 0) {
                throw new RuntimeException("设备仓匣号不在线,或者是仓匣id错误");
            }
            //修改用户记录里的仓匣归还状态
            if (!StringUtils.isEmpty(userLogId)) {
                TUserLog tUserLog = tUserLogMapper.selectTUserLogByUserId(Integer.parseInt(userLogId));
                if (tUserLog != null) {
                    if (tUserLog.getDrawerStu() == 0) {
                        throw new RuntimeException("用户记录出现错误");
                    }
                }
                tUserLog.setDrawerStu(0);
                tUserLog.setRemark("仓匣已归还到设备上,请及时补充消息");
                tUserLogMapper.updateTUserLog(tUserLog);
            }
            //修改之前drawerId 的状态
            tDrawerMapper.updateTDrawerDrawerId(drawerId);

            tDrawer.setDrawerStu(0);
            tDrawer.setDrawerId(drawerId);
            tDrawer.setDrawerRemark(drawer.getDrawerRemark());
            tDrawer.setToolId(drawer.getToolId());
            tDrawerMapper.updateTDrawer(tDrawer);
        } catch (RuntimeException e) {
            //上述步骤有错误
            //归还失败 数据回滚
            MqttVo mqttVo = new MqttVo();
            mqttVo.setCode(3);
            mqttVo.setUserLogId(userLogId);
            mqttVo.setDrawerId(drawerId);
            mqttVo.setEquipmentId(equipmentId);
            mqttVo.setDrawerNo(drawerNo);
            String payload = JSONObject.toJSONString(mqttVo);
            String json = EmqxUtils.publish(equipmentId + "/code", equipmentId, payload, QosEnum.QoS2, false, EmqxUtils.getUrl() + "/api/v4/mqtt/publish");
            //归还失败 修改备注
            TUserLog tUserLog = new TUserLog();
            tUserLog.setUserLogId(Integer.parseInt(userLogId));
            tUserLog.setDrawerStu(2);
            tUserLogMapper.updateTUserLog(tUserLog);
            e.printStackTrace();
        }
        return 0;

    }


}
